package github.kawaiior.yuanchuxiuzhen.common.item.misc;

import github.kawaiior.yuanchuxiuzhen.common.capability.entity.ManaPower;
import github.kawaiior.yuanchuxiuzhen.core.init.itemgroup.YcxzGroup;
import github.kawaiior.yuanchuxiuzhen.core.registry.ModCapability;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Food;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.common.util.LazyOptional;

import javax.annotation.Nullable;
import java.util.List;

public class PelletItem extends Item {
    private final ManaPower.ManaRoot manaRoot;

    private static final Food food = (new Food.Builder())
            .saturation(1)  // 饱腹度
            .hunger(1) // 鸡腿
            .setAlwaysEdible().build();

    public PelletItem(ManaPower.ManaRoot manaRoot) {
        super(new Properties().group(YcxzGroup.YCXZ_GROUP).food(food));
        this.manaRoot = manaRoot;
    }

    public PelletItem(ManaPower.ManaRoot manaRoot, Properties properties) {
        super(properties.food(food));
        this.manaRoot = manaRoot;
    }

    private void onUsed(PlayerEntity player, World world){
        // 使用妖丹后会获取经验值
        // 如果有对应的灵根，则会获得大量经验值
        LazyOptional<ManaPower> capability = player.getCapability(ModCapability.MANA_POWER);
        capability.ifPresent((power)->{
            if (power.hasManaRoot(this.manaRoot)){
                power.addExperience((int) (power.getMaxExperience()*0.05F), world, player);
            }else {
                power.addExperience((int) (power.getMaxExperience()*0.01F), world, player);
            }
        });
    }

    @Override
    public ItemStack onItemUseFinish(ItemStack stack, World world, LivingEntity entityLiving) {
        if (entityLiving instanceof PlayerEntity && !entityLiving.world.isRemote){
            onUsed((PlayerEntity) entityLiving, world);
        }
        return super.onItemUseFinish(stack, world, entityLiving);
    }

    public ManaPower.ManaRoot getManaRoot() {
        return manaRoot;
    }

    @Override
    public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {
        tooltip.add(new TranslationTextComponent("item.yuanchuxiuzhen.pellet.desc"));
        tooltip.add(new TranslationTextComponent("item.yuanchuxiuzhen.pellet.mana.root", this.manaRoot.toString()));
    }
}
